import { Provide, Inject } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { NursingPersonEntity } from '../../nursing/entity/person';
import { NurseInfoEntity } from '../../nurse/entity/info'
import { DictInfoEntity } from '../../dict/entity/info'

/**
 * 被护理人信息
 */
@Provide()
export class NursingAppPersonService extends BaseService {
  @InjectEntityModel(NursingPersonEntity)
  nursingPersonEntity: Repository<NursingPersonEntity>;

  @InjectEntityModel(NurseInfoEntity)
  nurseInfoEntity: Repository<NurseInfoEntity>;

  @InjectEntityModel(DictInfoEntity)
  dictInfoEntity: Repository<DictInfoEntity>;

  @Inject()
  ctx;

  async getNursing(BodyData) {
    let user = await this.nursingPersonEntity.createQueryBuilder()
      .where("familyUserId = :userId", { userId: this.ctx.user.id })
      .getMany()
    return user
  }

  async nursingCreate(BodyData) {
    let user = await this.nursingPersonEntity.findOneBy({ name: BodyData.name, familyUserId: this.ctx.user.id })
    if (!user) {
      BodyData.familyUserId = this.ctx.user.id
      console.log(this.ctx.user.id, 'this.ctx.header.authorId')
      let res = await this.nursingPersonEntity.save(BodyData)
      return res
    } else {
      throw new Error('当前被护理人已存在');
    }
  }

  // 删除护理人
  async nursingDelete(BodyData) {
    let user = await this.nursingPersonEntity.delete({ id: BodyData.id })
    return user
  }


  // 修改被护理人
  async nursingUpdate(BodyData) {
    let res = await this.nursingPersonEntity.update({
      id: BodyData.id,
    }, {
      name: BodyData.name,
      sex: BodyData.sex,
      birthday: BodyData.birthday
    })
  }

  // 获取护理人员列表
  async getNursingStaff(BodyData) {
    let data = await this.nurseInfoEntity.createQueryBuilder()
      .getMany()
    return data
  }

  // 获取服务类别
  async getServiceType(BodyData) {
    let data = []
    let res = await this.dictInfoEntity.createQueryBuilder()
    .andWhere({typeId:21})
    .getMany()
    data = res.filter( o => !o.parentId)
    data.forEach( o => {
      o.children = res.filter( o1 => o1.parentId == o.id)
    })
    console.log('res',data,'11')
    return data
  }
}
